import { createSlice, PayloadAction } from '@reduxjs/toolkit';

export interface Log {
  id: string;
  user: string;
  action: string;
  type: 'create' | 'update' | 'delete' | 'login';
  timestamp: string;
  details: string;
}

interface LogState {
  logs: Log[];
  loading: boolean;
  error: string | null;
}

const initialState: LogState = {
  logs: [],
  loading: false,
  error: null,
};

const logSlice = createSlice({
  name: 'log',
  initialState,
  reducers: {
    setLogs: (state, action: PayloadAction<Log[]>) => {
      state.logs = action.payload;
    },
    addLog: (state, action: PayloadAction<Log>) => {
      state.logs.push(action.payload);
    },
    updateLog: (state, action: PayloadAction<{ id: string; log: Partial<Log> }>) => {
      const index = state.logs.findIndex(log => log.id === action.payload.id);
      if (index !== -1) {
        state.logs[index] = { ...state.logs[index], ...action.payload.log };
      }
    },
    deleteLog: (state, action: PayloadAction<string>) => {
      state.logs = state.logs.filter(log => log.id !== action.payload);
    },
    setLoading: (state, action: PayloadAction<boolean>) => {
      state.loading = action.payload;
    },
    setError: (state, action: PayloadAction<string | null>) => {
      state.error = action.payload;
    },
  },
});

export const { setLogs, addLog, updateLog, deleteLog, setLoading, setError } = logSlice.actions;
export default logSlice.reducer;